package com.polaris.live.manager

import com.blankj.utilcode.util.StringUtils
import com.google.firebase.messaging.RemoteMessage
import com.polaris.live.common.cacha.DisplayUtil
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.im.manager.ImSessionManager
import com.polaris.live.im.sfs.bean.chat.ext.SingleMessageExtBean
import com.polaris.live.im.utils.SessionUtils
import com.polaris.live.resp.bean.PromptNoticeBean
import com.polaris.live.translation.R
import com.polaris.live.ui.game.GameUtils
import com.polaris.live.ui.live.activity.CallVideoActivity
import com.polaris.live.ui.live.activity.LiveSpectatorActivity
import com.polaris.live.ui.live.activity.LiveVideoActivity
import com.polaris.live.ui.main.activity.MainActivity
import com.polaris.live.ui.message.MessageActivity
import com.polaris.live.ui.message.MessageStrangerActivity
import com.polaris.live.ui.party.activity.PartyAnchorActivity
import com.polaris.live.ui.party.activity.PartySpectatorActivity
import com.polaris.live.ui.party.activity.game.PartyGameAnchorActivity
import com.polaris.live.ui.party.activity.game.PartyGameSpectatorActivity
import com.polaris.live.ui.party.activity.video.PartyVideoAnchorActivity
import com.polaris.live.utils.PushNoticeUtils
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.LinkedList

/**
 * PromptNoticeManager
 *
 * @author Created by lucas on 2023/12/12 12:58
 */
object PromptNoticeManager {

    private val mNoticeList = LinkedList<PromptNoticeBean>()

    /**
     * 显示提示
     */
    fun showNotice(message: RemoteMessage) {
        CoroutineScopeManager.mainScope.launch {
            resolvePromptNotice(message) { msg ->
                if (mNoticeList.isEmpty()) {
                    playNotice(msg)
                } else {
                    mNoticeList.add(msg)
                }
            }
        }
    }

    private fun replayNotice() {
        if (mNoticeList.isNotEmpty()) {
            playNotice(mNoticeList.poll())
        }
    }

    private fun playNotice(message: PromptNoticeBean) {
        CoroutineScopeManager.mainScope.launch {
            invokePlayNotice(message)
        }
    }

    private suspend fun invokePlayNotice(message: PromptNoticeBean) {
        val topActivity = ViewUtils.getAliveTopActivity()
        if ((topActivity is MainActivity && DisplayUtil.getPrimaryIdByCurrentIndex(topActivity.getCurrentIndex()) == DisplayUtil.MESSAGE)
            || topActivity is CallVideoActivity
            || topActivity is LiveVideoActivity
            || topActivity is MessageActivity
            || topActivity is LiveSpectatorActivity
            || topActivity is MessageStrangerActivity
            || topActivity is PartySpectatorActivity
            || topActivity is PartyAnchorActivity
            || topActivity is PartyGameSpectatorActivity
            || topActivity is PartyGameAnchorActivity
            || topActivity is PartyVideoAnchorActivity
            || GameUtils.gameRun
        ) {
            replayNotice()
            return
        }
        if (topActivity == null || topActivity.isFinishing || topActivity.isDestroyed) {
            mNoticeList.add(message)

            delay(1000)

            replayNotice()
            return
        }

        //响铃，先跟弹窗一起
        SessionUtils.noticeMessage()

        PushNoticeUtils.showViewNotice(topActivity, message) {
            replayNotice()
        }

//        val view = PushNoticeUtils.showNotice(topActivity, message) {
//            replayNotice()
//        }
//
//        delay(3000)
//
//        view.dismiss()
    }

    private fun resolvePromptNotice(
        remoteMessage: RemoteMessage,
        block: (PromptNoticeBean) -> Unit
    ) {
        val type = remoteMessage.data["type"]?.toIntOrNull() ?: return
        val title = remoteMessage.notification?.title
        val content = remoteMessage.notification?.body ?: return
        val image = remoteMessage.notification?.imageUrl?.toString()
        val router = remoteMessage.data["router"]
        val router2 = remoteMessage.data["router2"]
        val ext = remoteMessage.data["ext"]

        val bean = PromptNoticeBean(
            type = type,
            title = title,
            content = content,
            router = router,
            router2 = router2,
            ext = ext,
            image = image,
            timestamp = System.currentTimeMillis()
        )

        when (type) {
            //目前只有私聊消息需要做特殊处理
            TYPE_MESSAGE_SINGLE -> {
                val senderId = remoteMessage.data["senderId"]?.toLongOrNull() ?: return
                val seqId = remoteMessage.data["seqId"]?.toLongOrNull() ?: return
                val msgType = remoteMessage.data["msgType"]?.toLongOrNull() ?: return

                CoroutineScopeManager.ioScope.launch {
                    val extBean = try {
                        if (ext.isNullOrEmpty()) {
                            null
                        } else {
                            JsonUtils.fromJson<SingleMessageExtBean>(ext)
                        }
                    } catch (t: Throwable) {
                        t.printStackTrace()

                        null
                    }

                    val formatContent =
                        SessionUtils.formatSessionContext(msgType, senderId, content, extBean) ?: content

                    val readNumber = ImSessionManager.getSessionUnreadNumber(senderId, seqId)
                    val finalContent = if (readNumber > 1) {
                        "[$readNumber] $title: $formatContent"
                    } else {
                        formatContent
                    }

                    withContext(CoroutineScopeManager.mainDispatcher) {
                        block(
                            bean.copy(
                                content = finalContent
                            )
                        )
                    }
                }
            }
            TYPE_MESSAGE_SYSTEM -> {
                block(
                    bean.copy(
                        title = StringUtils.getString(R.string.app_name) + " " + StringUtils.getString(R.string.team)
                    )
                )
            }
            else -> {
                block(bean)
            }
        }
    }

    /**
     * 私聊消息类型
     */
    const val TYPE_MESSAGE_SINGLE = 0

    /**
     * 系统消息类型
     */
    const val TYPE_MESSAGE_SYSTEM = 1

    /**
     * 直播通知
     */
    const val TYPE_LIVE = 2

}